import { AxiosResponse } from "axios";

export function fileStreamDownload(res: AxiosResponse, customeFilename = "") {
    try {
        let data = res.data;
        if (!data) {
            return;
        }
        let url = window.URL.createObjectURL(new Blob([data]));
        let a: HTMLAnchorElement | null = document.createElement("a");
        let filename = customeFilename;
        if (!customeFilename) {
            const filenameRegex = /filename[^;=\n]*=(['"].*?\2|[^;\n]*)/;
            let disposition = res.headers["content-disposition"];
            let matches = filenameRegex.exec(disposition);
            // console.log(res);
            if (matches) {
                filename = decodeURI(matches[1]);
            }
        }
        if (a) {
            a.style.display = "none";
            a.href = url;
            a.setAttribute("download", filename);
            document.body.appendChild(a);
            a.click(); //执行下载
            a = null;
        }
    } catch (err) {
        console.log(err);
    }
}
